package com.itggm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itggm.DTO.CoursePageDTO;
import com.itggm.mapper.CourseMapper;
import com.itggm.pojo.Course;
import com.itggm.response.ResponseResult;
import com.itggm.service.CourseService;

import com.itggm.utils.AliOSSUtil;
import com.itggm.utils.StringUtil;
import com.itggm.vo.CourseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;


/**
 * @author: ggm
 * @data 2024年11月21日 20:03
 * 课程管理
 */
@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private AliOSSUtil aliOSSUtil;

    @Override
    public ResponseResult page(CoursePageDTO coursePageDTO) {
        PageHelper.startPage(coursePageDTO.getPage(), coursePageDTO.getLimit());
        List<CourseVO> courseVOList = courseMapper.selectCourses(coursePageDTO.getCourseName());
        long total = new PageInfo<CourseVO>(courseVOList).getTotal();
        return ResponseResult.success().count(total).data(courseVOList);


    }

    @Override
    public ResponseResult editCourseImg(String courseId, String fileName, String img) {
        String url = StringUtil.extractFileNameFromUrl(img);
        //删除原课程图片
        aliOSSUtil.delete(url);

        courseMapper.updateCourseImg(courseId, fileName);

        return ResponseResult.success().message("更新成功");
    }

    @Override
    public ResponseResult deleteCourse(String img) {
        Course course = courseMapper.getByImg(img);
        if (ObjectUtils.isEmpty(course.getCoachId())) {
            String url = StringUtil.extractFileNameFromUrl(img);
            aliOSSUtil.delete(url);
            courseMapper.delete(img);
            return ResponseResult.success().message("删除成功");
        }else {
            return ResponseResult.fail().message("该课程已关联教练，请等待教练结课再删除");
        }
    }

    @Override
    public ResponseResult addCoure(Course course) {
        courseMapper.addCourse(course);
        return ResponseResult.success().message("添加成功");
    }

    @Override
    public ResponseResult updateCoure(Course course) {
        courseMapper.updateCoure(course);
        return ResponseResult.success().message("修改成功");
    }

    @Override
    public ResponseResult getCoachInfo(Integer limit) {
        List<Course> courseList = courseMapper.select(limit);
        return ResponseResult.success().data(courseList);
    }

    @Override
    public ResponseResult getCourseList() {
        List<Course> courseList = courseMapper.getCourseList();
        return ResponseResult.success().data(courseList);
    }


}
